package com.hello.messagelistener;

import com.Constants;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * 这里演示的是不使用EnableRabbit+ RabbitListener注解接受消息的方式，
 * 而是使用实现MessageListener接口来实现消息接受的
 *
 * 一个MessageListenerContainer管理一个MessageListener，
 * 如果有多个MessageListener就注册多个MessageListenerContainer
 */
@Configuration
@ComponentScan("com.hello.messagelistener")
public class HelloMessageListenerMqConfiguration {


    @Autowired
    private ConsumerMessageListener consumerMessageListener;

    @Bean
    public CachingConnectionFactory connectionFactory() {
        return new CachingConnectionFactory("localhost");
    }

    @Bean
    public RabbitAdmin amqpAdmin() {
        return new RabbitAdmin(connectionFactory());
    }


    @Bean
    public Queue myQueue() {
        return new Queue(Constants.QUEUE_NAME);
    }


    @Bean
    public RabbitTemplate rabbitTemplate() {
        return new RabbitTemplate(connectionFactory());
    }

    @Bean
    public SimpleMessageListenerContainer messageListenerContainer() {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory());
        container.setQueueNames(Constants.QUEUE_NAME);
        container.setMessageListener(consumerMessageListener);

        return container;
    }
}
